package org.mspring.mlog.web.admin;

import org.apache.commons.lang3.StringUtils;
import org.mspring.mlog.cache.NodeCacheService;
import org.mspring.mlog.web.BaseAdminController;
import org.mspring.mlog.entity.NodeEntity;
import org.mspring.mlog.entity.UserEntity;
import org.mspring.mlog.common.constants.NodeType;
import org.mspring.nbee.web.support.WebContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author Gao Youbo
 * @since 2014年10月21日
 */
@Controller
@RequestMapping("/admin")
public class RedirectController extends BaseAdminController {

    private NodeCacheService nodeCacheService;

    @RequestMapping("/redirect")
    public String redirect(WebContext context, Model model) {
        String code = context.getRequiredParam("code");
        NodeEntity node = nodeCacheService.getNode(code);
        UserEntity user = getCurrentUser();
        List<NodeEntity> tabs = null;
        NodeEntity openTab = null;
        String url = "";
        if (node.getType().equals(NodeType.TREE_ITEM)) {
            tabs = nodeCacheService.getTabNode(node.getCode(), user.getId());
            if (tabs == null || tabs.isEmpty()) {
                if (StringUtils.isBlank(url)) {
                    // return prompt(model, "<font color=red>&lt;" +
                    // item.getName() + "&gt;</font> 未找到，或您无权访问该页面");
                }
            }
            if (tabs.isEmpty()) {
                openTab = tabs.get(0);
            } else {
                openTab = nodeCacheService.getOpenTabNode(node.getCode(), user.getId());
            }
            url = openTab.getUrl();
        } else if (node.getType().equals(NodeType.TAB)) {
            url = node.getUrl();
            openTab = node;
            tabs = nodeCacheService.getTabNode(openTab.getParentCode(), user.getId());
        }

        if (StringUtils.isBlank(url)) {
            // return prompt(model, "<font color=red>&lt;" + item.getName() +
            // "&gt;</font> 未找到，或您无权访问该页面");
        }
        model.addAttribute("tabs", tabs);
        model.addAttribute("openTab", openTab);
        return "/admin/redirect";
    }

    @Autowired
    public void setNodeCacheService(NodeCacheService nodeCacheService) {
        this.nodeCacheService = nodeCacheService;
    }
}
